package com.ruoyi.file.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.file.domain.SysStorageConfig;
import com.ruoyi.file.service.ISysStorageConfigService;
import com.ruoyi.file.service.storage.StorageService;
import com.ruoyi.file.service.storage.StorageServiceFactory;
import com.ruoyi.file.utils.StorageConfigUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * CORS配置控制器
 *
 * @author ruoyi
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/file/cors")
@Tag(name = "CORS配置管理", description = "存储桶CORS配置相关接口")
public class CorsController {

    private final ISysStorageConfigService storageConfigService;
    private final StorageServiceFactory storageServiceFactory;

    /**
     * 配置存储桶CORS - 解决前端跨域问题
     */
    @Operation(summary = "配置存储桶CORS")
    @SaCheckPermission("file:storage:cors")
    @PostMapping("/configure")
    public AjaxResult configureCors(@RequestParam(value = "configId", required = false) Long configId) {
        try {
            // 获取存储配置
            SysStorageConfig config = StorageConfigUtils.getAndValidateConfig(configId, storageConfigService);

            // 获取存储服务
            StorageService storageService = storageServiceFactory.getStorageService(config);


            // 配置CORS
            boolean success = storageService.configureBucketCors(config.getBucketName(), config);

            if (success) {
                // 根据存储类型返回不同的成功消息
                String successMsg = switch (config.getStorageType().toLowerCase()) {
                    case "minio" -> "MinIO存储桶已设置为公共读写权限，支持跨域访问和前端直传";
                    case "local" -> "本地存储不需要CORS配置";
                    case "tencent" -> "腾讯云COS CORS配置成功！已优化签名和头部设置，现在可以进行前端直传了";
                    case "aliyun" -> "阿里云OSS CORS配置成功，现在可以进行前端直传了";
                    case "aws" -> "AWS S3 CORS配置成功，现在可以进行前端直传了";
                    default -> "CORS配置成功，现在可以进行前端直传了";
                };


                return AjaxResult.success(successMsg);
            } else {
                log.error("CORS配置失败: configId={}, storageType={}, bucketName={}", 
                        config.getConfigId(), config.getStorageType(), config.getBucketName());
                return AjaxResult.error("CORS配置失败，请检查存储配置和网络连接");
            }
        } catch (Exception e) {
            log.error("配置CORS失败: configId={}, error={}", configId, e.getMessage(), e);
            
            // 根据错误类型提供更具体的错误信息
            String errorMsg = "配置CORS失败: ";
            if (e.getMessage() != null) {
                if (e.getMessage().contains("Access Denied") || e.getMessage().contains("403")) {
                    errorMsg += "访问被拒绝，请检查存储配置的访问密钥权限";
                } else if (e.getMessage().contains("NoSuchBucket") || e.getMessage().contains("404")) {
                    errorMsg += "存储桶不存在，请先创建存储桶";
                } else if (e.getMessage().contains("Network") || e.getMessage().contains("timeout")) {
                    errorMsg += "网络连接失败，请检查网络和访问地址配置";
                } else if (e.getMessage().contains("Invalid Param")) {
                    errorMsg += "CORS参数格式错误，系统已尝试自动修复，请重试或联系管理员";
                } else if (e.getMessage().contains("400")) {
                    errorMsg += "请求参数错误，可能是CORS配置格式不被腾讯云COS接受，系统已尝试备用配置";
                } else {
                    errorMsg += e.getMessage();
                }
            } else {
                errorMsg += "未知错误";
            }
            
            return AjaxResult.error(errorMsg);
        }
    }

    /**
     * 获取存储桶CORS配置状态
     */
    @Operation(summary = "获取CORS配置状态")
    @SaCheckPermission("file:storage:cors")
    @GetMapping("/status")
    public AjaxResult getCorsStatus(@RequestParam(value = "configId", required = false) Long configId) {
        try {
            // 获取存储配置
            SysStorageConfig config = StorageConfigUtils.getAndValidateConfig(configId, storageConfigService);

            // 获取存储服务
            StorageService storageService = storageServiceFactory.getStorageService(config);


            // 获取CORS配置状态
            String corsStatus = storageService.getBucketCors(config.getBucketName(), config);

            AjaxResult result = AjaxResult.success("获取CORS状态成功");
            result.put("status", corsStatus);
            result.put("bucketName", config.getBucketName());
            result.put("configName", config.getConfigName());
            result.put("storageType", config.getStorageType());
            result.put("endpoint", config.getEndpoint());
            
            // 添加针对腾讯云COS的特殊提示
            if ("tencent".equalsIgnoreCase(config.getStorageType())) {
                if (corsStatus.contains("未配置") || corsStatus.contains("不存在")) {
                    result.put("suggestion", "腾讯云COS需要配置CORS才能支持前端直传，请点击配置按钮进行设置");
                } else if (corsStatus.contains("配置完整")) {
                    result.put("suggestion", "腾讯云COS CORS配置正常，支持前端直传");
                } else if (corsStatus.contains("配置不完整")) {
                    result.put("suggestion", "腾讯云COS CORS配置不完整，建议重新配置以确保前端直传正常工作");
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取CORS状态失败: configId={}, error={}", configId, e.getMessage(), e);
            
            String errorMsg = "获取CORS状态失败: ";
            if (e.getMessage() != null) {
                if (e.getMessage().contains("Access Denied") || e.getMessage().contains("403")) {
                    errorMsg += "访问被拒绝，请检查存储配置的访问密钥权限";
                } else if (e.getMessage().contains("NoSuchBucket") || e.getMessage().contains("404")) {
                    errorMsg += "存储桶不存在";
                } else {
                    errorMsg += e.getMessage();
                }
            } else {
                errorMsg += "未知错误";
            }
            
            return AjaxResult.error(errorMsg);
        }
    }

    /**
     * 删除存储桶CORS配置
     */
    @Operation(summary = "删除CORS配置")
    @SaCheckPermission("file:storage:cors")
    @DeleteMapping("/delete")
    public AjaxResult deleteCors(@RequestParam(value = "configId", required = false) Long configId) {
        try {
            // 获取存储配置
            SysStorageConfig config = StorageConfigUtils.getAndValidateConfig(configId, storageConfigService);

            // 获取存储服务
            StorageService storageService = storageServiceFactory.getStorageService(config);

            // 删除CORS配置
            boolean success = storageService.deleteBucketCors(config.getBucketName(), config);

            if (success) {
                // 根据存储类型返回不同的成功消息
                String successMsg = switch (config.getStorageType().toLowerCase()) {
                    case "minio" -> "MinIO存储桶已设置为私有权限，关闭跨域访问";
                    case "local" -> "本地存储不需要CORS配置";
                    default -> "CORS配置已删除";
                };

                return AjaxResult.success(successMsg);
            } else {
                return AjaxResult.error("删除CORS配置失败");
            }
        } catch (Exception e) {
            log.error("删除CORS配置失败: {}", e.getMessage(), e);
            return AjaxResult.error("删除CORS配置失败: " + e.getMessage());
        }
    }
}
